# -*- coding: utf-8 -*-
'''
Created on 2011-3-7

@author: Tony
'''
"""
04
基于django的新浪微博oauth views
05
需要django的session支持
06
"""
import datetime
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User

from goplay.weibopy import OAuthHandler, oauth, WeibopError
from goplay.weibopy.api import API
from goplay.sinaweibo.models import UserInfo
from goplay.account import views
from goplay.sinaweibo.getFriends import getFriends



 

consumer_key = '3482834712' 
consumer_secret = '40c54f7f6730f543aed36b36f92ca06e'


class WebOAuthHandler(OAuthHandler):
    def get_authorization_url_with_callback(self, callback, signin_with_twitter=False):
        """Get the authorization URL to redirect the user"""
        try:
            # get the request token
            self.request_token = self._get_request_token()
            # build auth request and return as url
            if signin_with_twitter:
                url = self._get_oauth_url('authenticate')
            else:
                url = self._get_oauth_url('authorize')
            request = oauth.OAuthRequest.from_token_and_callback(token=self.request_token, callback=callback, http_url=url)
            return request.to_url()
        except Exception, e:
            raise WeibopError(e)
        



def _get_referer_url(request):
    referer_url = request.META.get('HTTP_REFERER', '/')
    host = request.META['HTTP_HOST']
    if referer_url.startswith('http') and host not in referer_url:
        referer_url = '/' # 避免外站直接跳到登录页而发生跳转错误
    return referer_url


def _oauth():
    """获取oauth认证类"""
    return WebOAuthHandler(consumer_key, consumer_secret)

def login(request):
    # 保存最初的登录url，以便认证成功后跳转回来
    back_to_url = _get_referer_url(request)
    request.session['login_back_to_url'] = back_to_url
    # 获取oauth认证url
    login_backurl = request.build_absolute_uri('/login_check')
    auth_client = _oauth()
    auth_url = auth_client.get_authorization_url_with_callback(login_backurl)
    # 保存request_token，用户登录后需要使用它来获取access_token
    request.session['oauth_request_token'] = auth_client.request_token
    # 跳转到登录页面
    return HttpResponseRedirect(auth_url)

"""用户成功登录授权后，会回调此方法，获取access_token，完成授权
   然后判断用户是否已经在user表中，没有的话加入；
   最后模拟用户直接登录"""
def login_check(request):
    verifier = request.GET.get('oauth_verifier', None)
    auth_client = _oauth()
    # 设置之前保存在session的request_token
    request_token = request.session['oauth_request_token']
    del request.session['oauth_request_token']
    auth_client.set_request_token(request_token.key, request_token.secret)
    access_token = auth_client.get_access_token(verifier)
    # 保存access_token，以后访问只需使用access_token即可
    request.session['oauth_access_token'] = access_token
    #获取登录用户
    api=API(auth_client)
    username=auth_client.get_username()
    #判读用户信息是否已经在数据库中，如果用户不存在，通过api获取用户的相关信息存储到数据库中
    user_exist=User.objects.filter(username=username)   
    if not user_exist:
        sinauserinfo=get_myself(api,username)
        ufnames=getFriends().myFriends(access_token.key,access_token.secret)
        User.objects.create_user(username,'','111111')
        User.objects.filter(username=username).update(first_name=username)
        sinauserinfo=UserInfo(username=sinauserinfo['name'],province=sinauserinfo['province'],city=sinauserinfo['city'],location=sinauserinfo['location'],profile_image=sinauserinfo['profile_image'],gender=sinauserinfo['gender'],friends=ufnames)
        sinauserinfo.save()
        
    #从数据库中取出用户id,并存储在session中调用
    '''userinfo=UserInfo.objects.filter(username=username).values('id','username','province','city','profile_image')
    if not userinfo:
        request.session['userinfo']=username
    else:
        cityName=Province.objects.filter(province_id=userinfo[0].get('province'),city_id=userinfo[0].get('city'))
        if not cityName:
            cityName=''
        else:
            cityName=cityName[0]
        userinfo[0]['cityname']=cityName
        request.session['userinfo']=userinfo[0]'''
    
    #模拟用户登录   
    if(views._login(request,username,"111111")):
        User.objects.filter(username=username).update(last_login=datetime.datetime.now())
        return HttpResponseRedirect(reverse('index'))
    else:
        return HttpResponseRedirect(reverse("login"))
    
    
    
    
    

'''def logout(request):
    """用户登出，直接删除access_token"""
    if request.session['oauth_access_token']:
        del request.session['oauth_access_token']
    else:
        auth_logout(request)
    del request.session['userinfo']
    #back_to_url = _get_referer_url(request)
    return HttpResponseRedirect(reverse("login"))'''

#获得登录用户的详细信息
def getAtt(obj,key):
    try:
        return obj.__getattribute__(key)
    except Exception, e:
        print e
        return ''

def get_myself(api,username):
        #myself = api.get_user(id=1684484080)
        myself = api.get_user(screen_name=username)
        obj = myself
        user={}
        user['id']=getAtt(obj,'id')
        user['profile_image'] = getAtt(obj,'profile_image_url')
        user['name']=getAtt(obj,"screen_name")
        user['description']=getAtt(obj,"description")
        user['city']=getAtt(obj,'city')
        user['province']=getAtt(obj,'province')
        user['location']=getAtt(obj,'location')
        user['gender']=getAtt(obj,'gender')
        #use = auth.get_username()
        return user

